package com.novel.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.novel.common.exception.CustomerException;
import com.novel.mapper.NovelMapper;
import com.novel.mapper.NovelRecommendMapper;
import com.novel.mapper.UserMapper;
import com.novel.pojo.novel.Novel;
import com.novel.pojo.novel.NovelRecommend;
import com.novel.pojo.system.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Slf4j
@Service
public class NovelRecommendService {

    @Autowired
    private NovelRecommendMapper recommendMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private NovelMapper novelMapper;

    /**
     * 根据作者id查询推荐票数量
     */
    public List<Map<String, Object>> getRecommendMap(String authorId) {
        return recommendMapper.queryNovelRecommendByAuthorId(authorId);
    }


    /**
     * 推荐小说
     * 1.添加推荐记录
     * 2.减少推荐票数量
     * 3.增加小说推荐票数
     *
     * @param recommend 小说推荐信息
     */
    @Transactional
    public boolean insertRecommendInfo(NovelRecommend recommend) {
        //数据校验
        if (StringUtils.isBlank(recommend.getUserId()) || StringUtils.isBlank(recommend.getNovelId())) {
            throw new CustomerException("关键参数不能为空!");
        }
        //查询用户信息
        User user = userMapper.selectByPrimaryKey(recommend.getUserId());

        if (user.getRecommend() < 1) {
            throw new CustomerException("推荐票数量不足!");
        }

        user.setRecommend(user.getRecommend() - 1);
        if (userMapper.updateByPrimaryKeySelective(user) == 1) {
            Novel novel = novelMapper.selectByPrimaryKey(recommend.getNovelId());
            novel.setNovelRecommend(novel.getNovelRecommend() + 1);
            if (novelMapper.updateByPrimaryKeySelective(novel) == 1) {
                //添加
                recommend.setId(UUID.randomUUID().toString());
                recommend.setCreatedTime(new Date());
                recommend.setAmount(1);
                recommend.setAuthorId(novel.getAuthorId());
                if (recommendMapper.insert(recommend) == 1) {
                    return true;
                }
            }
        }

        throw new CustomerException("推荐失败!");
    }


    /**
     * 分页查询推荐记录
     */
    public PageInfo<NovelRecommend> queryRecommendInfoByPage(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        return new PageInfo<>(recommendMapper.selectAll());
    }


}